#include "system_init.h"
#include "Usart.h"

/*******************************************************************************
**                     		   Global Functions 		             	      **
*******************************************************************************/
/**
 *  @brief :
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */

void Usart_Gpio_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;

  /* Configure PE1 remap mode */
  GPIO_InitStructure.m_Mode = GPIO_MODE_RMP;
  GPIO_InitStructure.m_OpenDrain = GPIO_POD_PP;
  GPIO_InitStructure.m_PullDown = GPIO_NOPULL;
  GPIO_InitStructure.m_PullUp = GPIO_NOPULL;
  GPIO_InitStructure.m_Speed = GPIO_LOW_SPEED;
  GPIO_InitStructure.m_Pin = GPIO_PIN_MASK_1;
  GPIO_Configuration(GPIOE_SFR, &GPIO_InitStructure);
  /* Configure PE0 remap mode, as RX pin, it should be pullup */
  GPIO_InitStructure.m_PullUp = GPIO_PULLUP;
  GPIO_InitStructure.m_Pin = GPIO_PIN_MASK_0;
  GPIO_Configuration(GPIOE_SFR, &GPIO_InitStructure);
  /* Configure PE1 remap function to AF11 */
  GPIO_Pin_RMP_Config(GPIOE_SFR, GPIO_Pin_Num_1, GPIO_RMP_PG1_AF11);
  /* Configure PE0 remap function to AF11 */
  GPIO_Pin_RMP_Config(GPIOE_SFR, GPIO_Pin_Num_0, GPIO_RMP_PG1_AF11);
}
/**
 *  @brief :
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void USART_Send(USART_SFRmap *USARTx, Usart_Sdu_Type *Usart_Sdu)
{
  for (uint32_t Send_data_count = 0; Send_data_count < Usart_Sdu->Length; Send_data_count++)
  {
    USART_SendData(USARTx, Usart_Sdu->Data[Send_data_count]);
    while (!USART_Get_Transmitter_Empty_Flag(USARTx))
      ;
  }
}

/**
 *  @brief :
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void USART_Mode_Config(USART_SFRmap *USARTx)
{
  USART_InitTypeDef USART_InitStructure;
  USART_Struct_Init(&USART_InitStructure);
  /* Set Usart To Async Mode */
  USART_InitStructure.m_Mode = USART_MODE_FULLDUPLEXASY;
  USART_InitStructure.m_TransferDir = USART_DIRECTION_FULL_DUPLEX;
  USART_InitStructure.m_WordLength = USART_WORDLENGTH_8B;
  USART_InitStructure.m_StopBits = USART_STOPBITS_1;

  /*  Set baudrate to 115200 */
  USART_InitStructure.m_BaudRateBRCKS = USART_CLK_HFCLK;
  USART_InitStructure.m_BaudRateInteger = 8;
  USART_InitStructure.m_BaudRateNumerator = 1;
  USART_InitStructure.m_BaudRateDenominator = 13;

  USART_Reset(USARTx);
  USART_Configuration(USARTx, &USART_InitStructure);
  USART_Passageway_Select_Config(USARTx, USART_U7816R_PASSAGEWAY_TX0);
  USART_RESHD_Enable(USARTx, TRUE);
  USART_Transmit_Data_Enable(USARTx, TRUE);
  USART_Cmd(USARTx, TRUE);
}

/**
 *  @brief :
 *  @param in :None
 *  @param out :None
 *  @retval :None
 */
void USART_Int_Config(USART_SFRmap *USARTx, InterruptIndex Peripheral)
{
	USART_Clear_Transmit_BUFR_INT_Flag(USARTx);

	USART_Receive_Idle_Frame_Config(USARTx, TRUE);
	USART_IDLE_INT_Enable(USARTx, TRUE);

//	USART_RDR_INT_Enable(USARTx, TRUE);
//	USART_TFE_INT_Enable(USARTx, TRUE);

	INT_Interrupt_Enable(Peripheral, TRUE);
}
